/*******************
 *
 * Copyright 1998-2017 IAR Systems AB.
 *
 * This is a template implementation of the "__read" function used by
 * the standard library.  Replace it with a system-specific
 * implementation.
 *
 * The "__read" function reads a number of bytes, at most "size" into
 * the memory area pointed to by "buffer".  It returns the number of
 * bytes read, 0 at the end of the file, or _LLIO_ERROR if failure
 * occurs.
 *
 * The template implementation below assumes that the application
 * provides the function "MyLowLevelGetchar".  It should return a
 * character value, or -1 on failure.
 *
 ********************/

#include <LowLevelIOInterface.h>
#include "stdio_cfg.h"

#pragma module_name = "?__read"

int MyLowLevelGetchar();

size_t __read(int handle, unsigned char * buffer, size_t size)
{
	/* Remove the #if #endif pair to enable the implementation */
#if 1

	int nChars = 0;

	for (/* Empty */; size > 0; --size)
	{
		int c;

		switch (handle)
		{
			case FILE_HANDLE_RSA_PUB_TXT:
				if (ras_pub.seek < ras_pub.size)
				{
					c = ras_pub.fil[ras_pub.seek++];
				}
				else
				{
					c = -1;
				}
				break;
			case FILE_HANDLE_RSA_PRIV_TXT:
				if (ras_priv.seek < ras_priv.size)
				{
					c = ras_priv.fil[ras_priv.seek++];
				}
				else
				{
					c = -1;
				}
				break;
			default:
				c = -1;
				break;
		}

		if (c < 0)
			break;

		*buffer++ = c;
		++nChars;
	}

	return nChars;

#else

	/* Always return error code when implementation is disabled. */
	return _LLIO_ERROR;

#endif
}
